<template>
  <el-card class="box-card" v-loading="loading">
    <div slot="header" class="clearfix">
      <span>警员排班统计</span>
      <el-button style="float: right; padding: 3px 0" type="text" @click="$emit('refresh')">刷新</el-button>
    </div>
    
    <div v-if="!officerId" class="empty-tip">
      请选择警员以查看详细统计
    </div>
    
    <div v-else class="stats-container">
      <div class="officer-info">
        <div class="avatar">
          <el-avatar :size="60" :src="officerInfo.avatar || defaultAvatar">{{ officerInfo.officerName && officerInfo.officerName.substring(0, 1) }}</el-avatar>
        </div>
        <div class="info">
          <h3>{{ officerInfo.officerName }}</h3>
          <p>{{ officerInfo.officerType }} | {{ officerInfo.department }}</p>
          <p>工号: {{ officerInfo.officerCode }}</p>
        </div>
      </div>
      
      <!-- 排班指标 -->
      <div class="metrics">
        <el-row :gutter="10">
          <el-col :span="8">
            <div class="metric-item">
              <div class="label">本月工时</div>
              <div class="value">{{ officerStats.monthHours || 0 }}小时</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="metric-item">
              <div class="label">夜班次数</div>
              <div class="value">{{ officerStats.nightShifts || 0 }}次</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="metric-item">
              <div class="label">休息天数</div>
              <div class="value">{{ officerStats.restDays || 0 }}天</div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 排班统计图表 -->
      <div class="charts-container">
        <div class="chart-title">班次分布</div>
        <div class="chart-item">
          <div ref="shiftDistributionChart" class="chart"></div>
        </div>
        <div class="chart-title">月度工时统计</div>
        <div class="chart-item">
          <div ref="monthlyWorkHoursChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 历史考核 -->
      <div class="assessment">
        <div class="chart-title">考核历史</div>
        <el-table :data="assessmentData" size="small" border style="width: 100%;">
          <el-table-column prop="month" label="月份" width="80"></el-table-column>
          <el-table-column prop="attendanceRate" label="出勤率">
            <template slot-scope="scope">
              <el-progress :percentage="scope.row.attendanceRate" :color="getAttendanceColor(scope.row.attendanceRate)"></el-progress>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="得分" width="80">
            <template slot-scope="scope">
              <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-card>
</template>

<script>
import * as echarts from 'echarts'
import { getOfficerAttendanceStats } from '@/api/bussiness/scheduling'

export default {
  name: 'OfficerStats',
  props: {
    officerId: {
      type: [Number, String],
      default: null
    },
    officerInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      defaultAvatar: require('@/assets/images/profile.jpg'),
      officerStats: {},
      assessmentData: [],
      shiftDistributionChart: null,
      monthlyWorkHoursChart: null
    }
  },
  watch: {
    officerId: {
      handler(newVal) {
        if (newVal) {
          this.getOfficerStats()
        } else {
          this.resetData()
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 监听窗口大小变化，动态调整图表大小
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // 移除监听器
    window.removeEventListener('resize', this.resizeCharts)
    this.disposeCharts()
  },
  methods: {
    // 调整图表大小
    resizeCharts() {
      if (this.shiftDistributionChart) {
        this.shiftDistributionChart.resize()
      }
      if (this.monthlyWorkHoursChart) {
        this.monthlyWorkHoursChart.resize()
      }
    },
    // 销毁图表
    disposeCharts() {
      if (this.shiftDistributionChart) {
        this.shiftDistributionChart.dispose()
        this.shiftDistributionChart = null
      }
      
      if (this.monthlyWorkHoursChart) {
        this.monthlyWorkHoursChart.dispose()
        this.monthlyWorkHoursChart = null
      }
    },
    // 获取警员统计数据
    getOfficerStats() {
      if (!this.officerId) return
      
      this.loading = true
      getOfficerAttendanceStats(this.officerId).then(res => {
        if (res.code === 200) {
          this.officerStats = res.data.stats || {}
          this.assessmentData = res.data.assessment || []
          
          this.$nextTick(() => {
            this.initCharts()
          })
        } else {
          this.$message.error('获取警员统计数据失败')
          // 使用模拟数据
          this.generateMockData()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        // 使用模拟数据
        this.generateMockData()
      })
    },
    // 生成模拟数据
    generateMockData() {
      this.officerStats = {
        monthHours: 168,
        nightShifts: 5,
        restDays: 8,
        shiftDistribution: [
          { name: '早班', value: 7 },
          { name: '中班', value: 6 },
          { name: '夜班', value: 5 },
          { name: '休息', value: 8 }
        ],
        monthlyWorkHours: [
          { month: '1月', hours: 176 },
          { month: '2月', hours: 160 },
          { month: '3月', hours: 184 },
          { month: '4月', hours: 168 },
          { month: '5月', hours: 176 },
          { month: '6月', hours: 168 }
        ]
      }
      
      this.assessmentData = [
        { month: '1月', attendanceRate: 98, score: 95 },
        { month: '2月', attendanceRate: 95, score: 92 },
        { month: '3月', attendanceRate: 100, score: 98 },
        { month: '4月', attendanceRate: 93, score: 85 },
        { month: '5月', attendanceRate: 96, score: 90 }
      ]
      
      this.$nextTick(() => {
        this.initCharts()
      })
    },
    // 重置数据
    resetData() {
      this.officerStats = {}
      this.assessmentData = []
      
      this.disposeCharts()
    },
    // 初始化图表
    initCharts() {
      this.initShiftDistributionChart()
      this.initMonthlyWorkHoursChart()
    },
    // 初始化班次分布图表
    initShiftDistributionChart() {
      const chartDom = this.$refs.shiftDistributionChart
      if (!chartDom) return
      
      if (this.shiftDistributionChart) {
        this.shiftDistributionChart.dispose()
      }
      
      this.shiftDistributionChart = echarts.init(chartDom)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '0',
          left: 'center',
          data: (this.officerStats.shiftDistribution || []).map(item => item.name)
        },
        series: [
          {
            name: '班次分布',
            type: 'pie',
            radius: '60%',
            center: ['50%', '45%'],
            data: this.officerStats.shiftDistribution || [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      this.shiftDistributionChart.setOption(option)
    },
    // 初始化月度工时图表
    initMonthlyWorkHoursChart() {
      const chartDom = this.$refs.monthlyWorkHoursChart
      if (!chartDom) return
      
      if (this.monthlyWorkHoursChart) {
        this.monthlyWorkHoursChart.dispose()
      }
      
      this.monthlyWorkHoursChart = echarts.init(chartDom)
      
      const monthlyData = this.officerStats.monthlyWorkHours || []
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '8%',
          top: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: monthlyData.map(item => item.month),
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '工时'
          }
        ],
        series: [
          {
            name: '工时',
            type: 'bar',
            barWidth: '60%',
            data: monthlyData.map(item => item.hours),
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      this.monthlyWorkHoursChart.setOption(option)
    },
    // 获取出勤率颜色
    getAttendanceColor(rate) {
      if (rate >= 95) return '#67C23A'
      if (rate >= 90) return '#E6A23C'
      return '#F56C6C'
    },
    // 获取得分样式
    getScoreClass(score) {
      if (score >= 90) return 'score-excellent'
      if (score >= 80) return 'score-good'
      if (score >= 60) return 'score-pass'
      return 'score-fail'
    }
  }
}
</script>

<style lang="scss" scoped>
.empty-tip {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.stats-container {
  height: calc(100vh - 130px);
  overflow-y: auto;
  padding-right: 5px;
}

.officer-info {
  display: flex;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  
  .avatar {
    margin-right: 15px;
  }
  
  .info {
    h3 {
      margin: 0 0 8px 0;
    }
    
    p {
      margin: 4px 0;
      color: #606266;
      font-size: 13px;
    }
  }
}

.metrics {
  margin-bottom: 15px;
  
  .metric-item {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    
    .label {
      font-size: 13px;
      color: #606266;
      margin-bottom: 8px;
    }
    
    .value {
      font-size: 16px;
      font-weight: bold;
      color: #409EFF;
    }
  }
}

.charts-container {
  margin-bottom: 15px;
  
  .chart-item {
    width: 100%;
    
    .chart {
      height: 200px;
      margin-bottom: 15px;
    }
  }
}

.chart-title {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.assessment {
  margin-bottom: 15px;
}

.score-excellent {
  color: #67C23A;
}

.score-good {
  color: #409EFF;
}

.score-pass {
  color: #E6A23C;
}

.score-fail {
  color: #F56C6C;
}
</style> 